package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.framework.config.TtsConfig;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;


public class BiaoBeiTts {

    private static Logger logger = LoggerFactory.getLogger(BiaoBeiTts.class);

    @Resource
    private TtsConfig ttsConfig;
    /**
     * 合成使用的地址信息，rate、language等参数在本demo固定，开发者如需调整，参考https://www.data-baker.com/specs/file/tts_api_restful
     */
    public static String ttsUrl = "https://openapi.data-baker.com/tts?access_token=%s&domain=1&rate=2&audiotype=%s&language=zh&voice_name=%s&speed=%s&volume=%s&text=%s";
    /**
     * 获取token的地址信息
     * https://openapi.data-baker.com/oauth/2.0/token?grant_type=client_credentials&amp;client_secret=YTgwZTJiZWEtOGQ3Ni00**********yOWQ5YzNm&amp;client_id=43478949-293e********133ff2c301c8
     *
     */
    public static String tokenUrl = "https://openapi.data-baker.com/oauth/2.0/token?grant_type=client_credentials&client_secret=%s&client_id=%s";
    public static String clientId = "197afddeb91c45b9bc9ca7c07ae6f22b";
    public static String clientSecret = "7b601c2ddc1942d0946e26f718c79da8";
    public static String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiKiJdLCJzY29wZSI6WyJ0dHMtb25lc2hvdCJdLCJleHAiOjE2NDg4ODY0NDAsImF1dGhvcml0aWVzIjpbIioiXSwianRpIjoiYTIxMDA5ZTYtNzVjYS00MzAzLTk1YmMtZmYyZmNjMDY5YTE0IiwiY2xpZW50X2lkIjoiMTk3YWZkZGViOTFjNDViOWJjOWNhN2MwN2FlNmYyMmIifQ.Hzs6zeVpPEt5AG0KLlVWhqn0iLme9ofmSeuLaggPRq4";



    /**
     * 仅作为demo示例
     * 失败重试、token过期重新获取、日志打印等优化工作需要开发者自行完成
     **/
    public static String mkMp3ByBb(String idSeq,String content,int speed) {

        if (content.length()>300) {
            logger.warn("内容大于300");
        }

        String filePath = RuoYiConfig.getUploadPath();
        filePath = filePath + "/audio/"+idSeq+".mp3";

        String accessToken = token;
        if ("".equals(accessToken)) {
            accessToken = getAccessToken();
        }
        if (StringUtils.isNotEmpty(accessToken)) {
            doSynthesis(accessToken, "Beiru", content, 3, 5.0, 5.0, filePath);
        }
        return "ok";
    }

    public static void doSynthesis(String accessToken, String voiceName, String originText, Integer audioType, Double speed, Double volume, String filePath) {
        //在非浏览器上操作，需要把合成文本转化为utf-8格式
        try {
            originText = URLEncoder.encode(originText, "utf-8");
            String synthesisUrl = String.format(ttsUrl, accessToken, audioType, voiceName, speed, volume, originText);
            fetchTtsResponse(synthesisUrl, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求并获取音频流保存至本地文件：这里filePath为全路径
     *
     * @param url
     * @param filePath
     * @throws IOException
     */
    public static void fetchTtsResponse(String url, String filePath) throws IOException {
        OkHttpClient client = new OkHttpClient();
        //request 默认是get请求
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                if (response.body() != null&&response.body().contentType().toString().startsWith("audio")) {
                    //写入文件
                    File targetFile = new File(filePath);
                    Files.write(targetFile.toPath(), response.body().bytes());
                } else {
                    logger.warn("上传mp3失败:"+response.body().contentType().toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getAccessToken() {
        String accessToken = "";
        OkHttpClient client = new OkHttpClient();
        //request 默认是get请求
        String url = String.format(tokenUrl, clientSecret, clientId);
        Request request = new Request.Builder().url(url).build();
        JSONObject jsonObject;
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                //解析
                String resultJson = response.body().string();
                jsonObject = JSON.parseObject(resultJson);
                accessToken = jsonObject.getString("access_token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
}
